package com.gao.common;

import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 缓存所有服务器节点信息
 */
@Component
public class ServerCache {
    private static Logger logger = LoggerFactory.getLogger(ServerCache.class) ;

    @Autowired
    private LoadingCache<String, String> cache;

    @Value("${spring.hash_node}")
    private List<String> serverList;

    public void addCache(String key) {
        cache.put(key, key);
    }

    /**
     * 获取服务器节点
     * @return
     */
    public List<String> getServerList() {
        List<String> list = new ArrayList<>();

        if (cache.size() == 0) {
            for (String node : serverList) {
                addCache(node);
            }
        }

        for (Map.Entry<String, String> entry : cache.asMap().entrySet()) {
            list.add(entry.getKey());
        }
        return list;
    }

    /**
     * 更新所有缓存/先删除 再新增
     *
     * @param currentChildren
     */
    public void updateCache(List<String> currentChildren) {
        cache.invalidateAll();
        for (String currentChild : currentChildren) {
            // currentChildren = 127.0.0.1:9999
            addCache(currentChild);
        }
    }

    /**
     * 更新缓存
     */
    public void rebuildCacheList(){
        updateCache(getServerList()) ;
    }
}
